﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Azad.BCL;
using Azad;
using BCL.Entity;
using System.Web.UI.HtmlControls;
using NazSoft.Framework;

public partial class _Default : System.Web.UI.Page
{

    protected string _logoId = string.Empty;

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request.QueryString["mp"] == "b")
        {
            this.MasterPageFile = "~/BlankMasterPage.master";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var collection = Request.QueryString;
        String mn = collection["mn"] ?? string.Empty; // menu name
        string mp = collection["mp"];
        bool preview = Convert.ToBoolean(collection["preview"]);
        bool isHome = false;


        if (Page.IsPostBack == false)
        {
            SilverlightService silverlightService = new SilverlightService();
            var today = DateTimeUtilities.GetDateFromQueryString(collection);

            var logoInfo = silverlightService.GetByCurrentId(today, preview);
            if (logoInfo != null)
            {
                _logoId = Convert.ToString(logoInfo.Id);

                // over-ride date here to be used later in databound method
                //today = logoInfo.CurrentDate;

                // first get the details of specific menu
                var details = logoInfo.Detail.Where(x => x.MenuName == mn).FirstOrDefault();
                CurrentUrl = logoInfo.Url;
                if (String.IsNullOrEmpty(mn))
                {
                    isHome = true;
                }

                if (isHome)
                {
                    var details1 = logoInfo.Detail.Take(12);
                    divDefaultText.Visible = true;
                    //CoverPagePlaceHolder1.Visible = true;
                    //ConverPageImage.ImageUrl = logoInfo.LogoImage;
                    //CoverPageLink.NavigateUrl = logoInfo.Url + "current-magazine";
                }
                else
                {
                    divDefaultText.Visible = false;
                }

                List<LogoDetailDetail> itemsList = null;

                var pageSize = 0;

                if (details != null)
                {
                    itemsList = details.DetailToDetail;
                    pageSize = details.NoOfFilePerPage;
                }
                else
                {
                    // only search for isHome items if no menu name is defined in querystring
                    if (String.IsNullOrEmpty(mn))
                    {
                        itemsList = new List<LogoDetailDetail>();

                        // find all items of is home
                        foreach (var item in logoInfo.Detail)
                        {
                            var d = item.DetailToDetail.Where(x => x.IsHome == true);
                            itemsList.AddRange(d);
                        }

                        if (itemsList == null || itemsList.Count == 0)
                        {
                            foreach (var item in logoInfo.Detail)
                            {
                                var d = item.DetailToDetail.Where(f => f.IsHome == false);
                                itemsList.AddRange(d);
                            }
                            itemsList = itemsList.Take(12).ToList();

                        }
                    }
                }

                var currentPage = (collection["page"].ToInt32Safe());
                BindData(itemsList, pageSize, currentPage, logoInfo.Url, mn);


            }
            else
            {
                //NewsNotFoundMessage.Visible = true;
                //NewsThumbnails.Visible = false;
                NextPageHyperlink.Visible = false;
                PrevPageHyperLink.Visible = false;
            }
        }

    }

    public string CurrentUrl { get { return ViewState["test"] as string; } set { ViewState["test"] = value; } }


    private void BindData(List<LogoDetailDetail> itemsList, int pageSize, int currentPage, string url, string mn)
    {
        if (itemsList != null)
        {

            var itemsCount = itemsList.Count;
            pageSize = 1000;//== 0 ? 12 : pageSize;

            currentPage = currentPage == 0 ? 1 : currentPage;

            var recordsToSkip = (currentPage - 1) * pageSize;
            var totalPages = Math.Ceiling((double)(itemsCount / (double)pageSize));

            var dataToDisplay = itemsList.Skip(recordsToSkip).Take(pageSize);



            #region bind to ui
            NewsThumbnails.DataSource = dataToDisplay;
            NewsThumbnails.DataBind();
            #endregion



            #region show hide next prev page links
            if (currentPage == 1)
            {
                if (itemsCount > pageSize)
                {
                    NextPageHyperlink.Visible = true;
                    PrevPageHyperLink.Visible = false;
                }
                else
                {
                    NextPageHyperlink.Visible = false;
                    PrevPageHyperLink.Visible = false;
                }
            }
            else if (currentPage == totalPages)
            {
                NextPageHyperlink.Visible = false;
                PrevPageHyperLink.Visible = true;
            }
            else
            {
                NextPageHyperlink.Visible = true;
                PrevPageHyperLink.Visible = true;
            }
            #endregion



            #region create url of next prev page links
            {
                var navigateUrl = url;

                if (String.IsNullOrEmpty(mn) == false)
                {
                    navigateUrl = navigateUrl + mn + "/";
                }

                NextPageHyperlink.NavigateUrl = navigateUrl + "" + (currentPage + 1);
                PrevPageHyperLink.NavigateUrl = navigateUrl + "" + (currentPage - 1);


                //if (mp == "b")
                //{
                //    NextPageHyperlink.NavigateUrl = NextPageHyperlink.NavigateUrl + "?mp=b";
                //    PrevPageHyperLink.NavigateUrl = PrevPageHyperLink.NavigateUrl + "?mp=b";
                //}
            }
            #endregion

        }
        else
        {
            NoNewsMessage.Visible = true;
            NewsThumbnails.Visible = false;
            NextPageHyperlink.Visible = false;
            PrevPageHyperLink.Visible = false;
        }

    }


    private void SetMagnify()
    {

        if (Request.QueryString["mag"] == "true")
        {
            string query = @"jQuery(document).ready(function ($) { 
                    $('.magnifiable').each(function(){

                            $(this).addpowerzoom({defaultpower: 1.4,
                        

                            powerrange: [80, 80],largeimage: true,magnifiersize: [500, 200] }); 
                        });

});";
            //query = string.Format(query, imgFarman.ClientID);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Farman", query, true);

        }
        else
        {

            if (Request.QueryString["mag"] == "false")
            {
                Session["Magni"] = null;
            }





            if (!string.IsNullOrEmpty(Convert.ToString(Session["Magni"])))
            {
                string query = @"jQuery(document).ready(function ($) { 
                    $('.magnifiable').each(function(){

                            $(this).addpowerzoom({defaultpower: 1.4,
                        

                            powerrange: [80, 80],largeimage: true,magnifiersize: [500, 200] }); 
                        });

});";
                //query = string.Format(query, imgFarman.ClientID);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "LogoDetailDetail", query, true);


            }
        }
    }
    protected void NewsThumbnails_ItemCreated(object sender, RepeaterItemEventArgs e)
    {

    }
    protected void NewsThumbnails_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        HtmlAnchor anchor = e.Item.FindControl("news_image") as HtmlAnchor;
        if (null != anchor)
            anchor.HRef = anchor.HRef + "&current=" + CurrentUrl;
    }
    protected void NewsThumbnails_DataBound(object sender, EventArgs e)
    {

    }

}